<template>
  <top-main :page="home"></top-main>
  <div class="login-page">
      <div class="login-content">
        <div class="login-left-logo">
            <img src="../../a-images/login-logo.jpg" alt="">
        </div>
        <div class="login-right-form">
             <el-card class="login-form">
              <div class="auth-title">{{ isRegisterMode ? '注册' : '登录' }}</div>
              <div v-if="!isRegisterMode" class="login-style">
                  <el-form ref="loginForm" :model="form" :rules="rules">
                    <el-form-item prop="username">
                        <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="danger" class="login-btn" @click=handleLogin>登录</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="text" class="forgot-password">忘记密码</el-button>
                        <el-button type="text" class="to-register" @click="toggleMode">免费注册</el-button>
                    </el-form-item>
                </el-form>
              </div>
              <div v-else class="register-style">
                  <el-form ref="regForm" :model="registerForm" :rules="registerRules">
                          <el-form-item prop="username">
                              <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
                          </el-form-item>
                          <el-form-item prop="password">
                              <el-input v-model="registerForm.password" type="password" placeholder="请输入密码"></el-input>
                          </el-form-item>
                          <el-form-item prop="confirmPassword">
                              <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
                          </el-form-item>
                          <el-form-item>
                              <el-button type="primary" class="register-btn" @click="handleRegister">注册</el-button>
                          </el-form-item>
                          <el-form-item>
                              <el-button type="text"@click="toggleMode">已有账号？去登录</el-button>
                          </el-form-item>
                      </el-form>
              </div>
             </el-card>
        </div>
      </div>                                                                                                                                                                          
  </div>
  <local-bottom></local-bottom>
</template>
<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';
import LocalBottom from "@/1-classify/local-bottom.vue";
import TopMain from "@/1-topBar/topMain.vue";
const router = useRouter();

// 使用ref定义状态和表单数据
const loginForm = ref(null);
const regForm = ref(null);
const isRegisterMode = ref(false);

// 对表单数据的定义进行了一些调整，以增强可读性
const form = ref({
  username: '',
  password: '',
});

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
});

// 将验证规则定义为computed属性，以增强可维护性
const rules = computed(() => ({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}));

const registerRules = computed(() => ({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' },
  ],
}));

// 定义验证函数
const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

// 切换登录/注册模式
const toggleMode = () => {
  isRegisterMode.value = !isRegisterMode.value;
};

// 登录逻辑，增加了错误处理的细节
const handleLogin = async () => {
  try {
    await loginForm.value.validate();
    const response = await axios.post('http://localhost:8080/user/login', form.value);
    if (response.data.code===1) {
      sessionStorage.setItem('token', response.data.data);
      ElMessage.success('登录成功！');
      router.push('/');
    } else {
      throw new Error('用户名或密码错误');
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.message || '登录失败');
    } else {
      ElMessage.error('登录失败');
    }
  }
};

// 注册逻辑，同样增加了详细的错误处理
const handleRegister = async () => {
  try {
    await regForm.value.validate();
    const response = await axios.post('http://localhost:8080/user/register', registerForm.value);
    if (response.data.code===1) {
      ElMessage.success('注册成功！');
      router.push('/login');
    } else {
      throw new Error('注册失败');
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.message || '注册失败');
    } else {
      ElMessage.error('注册失败');
    }
  }
};
</script>
<style scoped lang="scss">
.login-page {
  width: 100%;
  height: 600px;
  background-color: #17073d;
  display: flex;
  align-items: center;

  .login-content {
      width: 75%;
      height: 400px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .login-left-logo {
          width: 720px;
          height: 100%;
      }
      .login-right-form{
          width: 350px;
          height: 330px;
          display: flex;
          align-items: center;
          
          .login-form{
              width: 100%;
              height: 90%;
              .auth-title{
                font-size: 20px;
                font-weight: bold;
                margin-bottom: 20px;
              }
              .login-btn{
                  width: 100%;
                  height: 40px;
                  font-size: 20px;
              }
              .register-btn{
                width: 100%;
              }
          }
      }
  }
}
</style>